﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
using Psm.Configuration;

namespace Psm.Container
{   
    public class Repository
    {
        private static CompositionContainer Instance { get; set; }

        public static void Initialize()
        {
            if (Instance == null)
            {
                var catalog = new AggregateCatalog(new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory, "*.dll"));
                Instance = new CompositionContainer(catalog);
            }
        }

        public static T GetInstance<T>()
        {
            return Instance.GetExportedValue<T>();
        }

        public static T GetInstance<T>(string composition)
        {
            return Instance.GetExportedValue<T>(composition);
        }

        public static T GetInstance<T>(string composition, string configuration) 
        {
            T instance = GetInstance<T>(composition);
            if (!string.IsNullOrWhiteSpace(configuration))
            {
                IConfigurable configurable = instance as IConfigurable;
                if (configurable == null)
                    throw new Exception(string.Format("Composition:{0},Configuration:{1} is not configurable", composition, configuration));
                configurable.Configure(configuration);
            }
            return instance;
        }
    }
}
